import re,os
from faker import Faker
from tools.log_control import ERROR
import jsonpath
from tools.cache_control import Cache
from config.configs import Config
import time


class MyMetaClass(type):
    def __getattr__(self, item):
        return os.environ[item]


class MyClass(metaclass=MyMetaClass):
    pass


class Context:
    def __init__(self):
        self.f = Faker(locale='zh_CN')

    @property
    def get_host11(self):
        #判断环境，testing，staging,prod, testing-global, staging-global，.0

        return Config().get_host11()


    @property
    def get_female_name(self) -> str:
        return self.f.name()+ str(self.get_now_time)

    @property
    def get_female_phone(self) -> str:
        return self.f.phone_number()

    @property
    def get_password(self):
        return Config().__getattr__("dm_password")

    @property
    def get_now_time(self):
        now = time.time()
        return int(round(now * 1000))


    @property
    def insert_vin(self):
        return "zidh"+ str(self.get_now_time)


def regular(target) -> str:
    """
    使用正则替换请求数据
    target:yaml的用例数据
    :return:
    """
    try:
        # 匹配规则
        regular_pattern = r'\${{(.*?)}}'
        while re.findall(regular_pattern, target):
            # group(1) 列出第一个括号匹配部分,host
            key = re.search(regular_pattern, target).group(1)
            # print("str(getattr(Context(), key))",str(getattr(Context(), key)))
            # str(getattr(Context(), key)),返回 ：https://tsp.testing.davincimotor.com
            try:
                target = re.sub(regular_pattern, str(getattr(MyClass, key)), target, 1)
            except KeyError:
                target = re.sub(regular_pattern, str(getattr(Context(), key)), target, 1)
                # return target
        return target
    except AttributeError:
        ERROR.logger.error('未找到对应的替换数据，请检查数据是否存在', target)
    raise


def sql_json(js_path, res):
    return jsonpath.jsonpath(res, js_path)[0]


def sql_regular(value, res=None):
    """
    这里处理sql中的依赖数据，通过获取接口响应的jsonpath的值进行替换
    :param res: jsonpath使用的返回结果
    :param value:
    :return:
    """
    sql_json_list = re.findall(r"\$json\((.*?)\)\$", value)

    for i in sql_json_list:
        pattern = re.compile(r'\$json\(' + i.replace('$', "\$").replace('[', '\[') + r'\)\$')
        key = str(sql_json(i, res))
        value = re.sub(pattern, key, value, count=1)
        value = sql_regular(value, res)

    return value



def cache_regular(value):
    """
    通过正则的方式，读取缓存中的内容
    例：$cache{login_init}
    :param value:
    :return:
    """
    # 正则获取 $cache{login_init}中的值 --> login_init
    regular_dates = re.findall(r"\$cache\{(.*?)\}", value)

    # 拿到的是一个list，循环数据
    for regular_data in regular_dates:
        value_types = ['int:', 'bool:', 'list:', 'dict:', 'tuple:', 'float:']
        if any(i in regular_data for i in value_types) is True:

            value_types = regular_data.split(":")[0]
            pattern = re.compile(r'\'\$cache{' + regular_data+ r'(.*?)}\'')
            regular_data = regular_data.split(":")[1]

        else:
            pattern = re.compile(r'\$cache\{' + regular_data.replace('$', "\$").replace('[', '\[') + r'\}')
        cache_data = Cache(regular_data).get_cache().replace(r'\n','').replace(r'\u2005', '')
        value = re.sub(pattern, cache_data, value)
    return value

if __name__ == '__main__':
    # res = regular("${{get_host11}}")
    # print(res)
    # aa = '$cache{login_token}'
    # ress = cache_regular(aa)
    # print(ress)

    a = Context().get_host11()
    print(a)
